<script setup lang="ts">
import { getRoleList } from "@/api/system/role/role";
import {
  deleteUsers,
  getUser,
  getUserList,
  upUser,
  upUserRole,
} from "@/api/system/user/user";
import type { FormInstance } from "element-plus";
import { reactive, ref, toRefs } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import type { UploadProps } from "element-plus";
import { addDateRange } from "@/utils/ruoyi";
interface User {
  userId: number;
  username: string;
  password: string;
  nickname: string;
  mobile: string;
  email: string;
  avatar: string;
  status: number;
  deptId: number;
  isDeleted: number;
  roleId: number;
  roleName: string;
  createTime: string;
  updateTime: string;
  pageNum?: number;
  pageSize?: number;
}
const formRef = ref();
const dialogVisible = ref(false);
const roleList = ref();
const userList = ref();
const tableRef = ref();
const total = ref(0);
const searchRef = ref();
const dateRange = ref();
const loading = ref(true);
// 表单规则校验
const passwordValidator = (rule: any, value: any, callback: any) => {
  if (!value.trim()) {
    callback(new Error("不能为空"));
  } else if (value.trim().length < 1 || value.trim().length > 20) {
    callback(new Error("长度为1到20位"));
  } else {
    callback();
  }
};
const roleValidator = (rule: any, value: any, callback: any) => {
  if (value == null) {
    callback(new Error("必须选择角色"));
  } else {
    callback();
  }
};

const data = reactive({
  form: <User>{},
  queryParams: <User>{
    pageNum: 1,
    pageSize: 10,
  },
  rules: {
    password: [
      { required: true, validator: passwordValidator, trigger: ["blur", "change"] },
    ],
    roleId: [{ required: true, validator: roleValidator, trigger: ["blur", "change"] }],
  },
});
const { queryParams, form, rules } = toRefs(data);
//获取用户列表
async function getUsers() {
  loading.value = true;
  await getUserList(addDateRange(queryParams.value, dateRange.value)).then((response) => {
    userList.value = response.data.rows;
    total.value = response.data.total;
  });
  loading.value = false;
}
//获取角色列表
function getRoles() {
  getRoleList().then((response) => {
    roleList.value = response.data.rows;
  });
}
//表单重置
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};
// 选择分页
const handleSizeChange = (val: number) => {
  queryParams.value.pageSize = val;
  getUsers();
};
// 当前页
const handleCurrentChange = (val: number) => {
  queryParams.value.pageNum = val;
  getUsers();
};

//查询按钮
const selectSumbit = () => {
  queryParams.value.pageNum = 1;
  getUsers();
};
//false是修改true是授权
const isSumbit = ref(true);
// 修改按钮
const EditSumbit = (row: any) => {
  resetForm(formRef.value);
  isSumbit.value = false;
  roleDisabled.value = true;
  userDisabled.value = false;
  dialogVisible.value = true;
  getUser(row.userId).then((response) => {
    form.value = response.data.data;
  });
};

const handleSelectionChange = (newSelection: User[]) => {
  selectedRows.value = newSelection;
  selectedRows.value.length === 0
    ? (iSdeleteUsersButton.value = true)
    : (iSdeleteUsersButton.value = false);
};
const selectedRows = ref<User[]>([]);
// 单个删除按钮
const handleDelete = async (row: User) => {
  await deleteUsers([row.userId]).then((response) => {
    ElMessage.success(response.data.msg);
  });
  getUsers();
};
const iSdeleteUsersButton = ref(true);
// 批量删除按钮
const deleteUsersButton = async () => {
  const ids = selectedRows.value.map((item) => item.userId);

  await ElMessageBox.confirm("确定要删除用户这些id为 " + ids + " 的用户吗吗？", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  });
  // 调用删除接口
  await deleteUsers(ids).then((response) => {
    ElMessage.success(response.data.msg);
  });
  // 更新表格数据（过滤掉已删除项）
  getUsers();
};
// 用户授权开关
const roleDisabled = ref(true);
//  修改用户基本信息开关
const userDisabled = ref(false);
// 授权按钮
const Empowering = (row: any) => {
  resetForm(formRef.value);
  isSumbit.value = true;
  userDisabled.value = true;
  roleDisabled.value = false;
  getUser(row.userId).then((response) => {
    form.value = response.data.data;
  });
  dialogVisible.value = true;
};

//提交按钮
const submitForm = (formRef: FormInstance | undefined) => {
  if (!formRef) return;
  formRef.validate(async (valid, fields) => {
    if (valid) {
      if (isSumbit.value) {
        await upUserRole(form.value).then((response) => {
          ElMessage.success(response.data.msg);
        });
      } else {
        await upUser(form.value).then((response) => {
          ElMessage.success(response.data.msg);
        });
      }
      dialogVisible.value = false;
      getUsers();
    } else {
      console.log("error submit!", fields);
    }
  });
};
// 头像上传成功回调
const handleAvatarSuccess: UploadProps["onSuccess"] = (response, uploadFile) => {
  form.value.avatar = response.data;
};
// 头像上传规则
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  if (
    rawFile.type !== "image/jpeg" &&
    rawFile.type !== "image/png" &&
    rawFile.type !== "image/gif"
  ) {
    ElMessage.error("头像必须是jpeg | png | gif");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error("Avatar picture size can not exceed 2MB!");
    return false;
  }
  return true;
};

// const deleteUsers = () => {};
// const resetButton = () => {
//   resetForm(formRef.value);
//   getUsers();
// };
// 加载头像失败回退
const errorHandler = () => true;
getRoles();
getUsers();
</script>
<template>
  <div class="common-layout">
    <el-container>
      <el-header style="margin: auto; max-width: 95%; height: auto">
        <el-form :inline="true" :model="queryParams" ref="searchRef" label-width="68px">
          <el-form-item prop="userId"
            ><el-input
              v-model="queryParams.userId"
              clearable
              placeholder="请输入用户id"
              style="width: 240px"
          /></el-form-item>

          <el-form-item prop="username">
            <el-input
              v-model="queryParams.username"
              clearable
              placeholder="请输入用户名"
              style="width: 240px"
          /></el-form-item>

          <el-form-item prop="nickname"
            ><el-input
              v-model="queryParams.nickname"
              clearable
              placeholder="请输入用户昵称"
              style="width: 240px"
            />
          </el-form-item>

          <el-form-item prop="mobile"
            ><el-input
              v-model.number="queryParams.mobile"
              clearable
              placeholder="请输入手机号"
              style="width: 240px"
            />
          </el-form-item>

          <el-form-item prop="email"
            ><el-input
              v-model="queryParams.email"
              clearable
              placeholder="请输入邮箱地址"
              style="width: 240px"
            />
          </el-form-item>

          <el-form-item prop="status">
            <el-select
              v-model="queryParams.status"
              placeholder="请选择状态"
              style="width: 240px"
            >
              <el-option label="停用" :value="0" />
              <el-option label="正常" :value="1" />
            </el-select>
          </el-form-item>

          <el-form-item prop="roleId">
            <el-select
              v-model="queryParams.roleId"
              placeholder="请选择角色"
              style="width: 240px"
            >
              <el-option
                v-for="item in roleList"
                :key="item.roleId"
                :label="item.roleName"
                :value="item.roleId"
              />
            </el-select>
          </el-form-item>

          <el-form-item prop="dateRange">
            <el-date-picker
              v-model="dateRange"
              value-format="YYYY-MM-DD"
              type="daterange"
              range-separator="-"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="selectSumbit">查询</el-button>
            <el-button
              type="primary"
              @click="resetForm(searchRef), (dateRange = null), getUsers()"
              plain
              >重置</el-button
            >
            <el-button
              type="danger"
              @click="deleteUsersButton"
              :disabled="iSdeleteUsersButton"
              >批量删除</el-button
            >
          </el-form-item>
        </el-form>
      </el-header>
      <el-main style="margin: auto; width: 95%">
        <el-divider />
        <el-table
          class="table"
          v-loading="loading"
          ref="tableRef"
          :data="userList"
          style="height: 90%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column fixed type="selection" width="55" />
          <el-table-column prop="userId" label="id" />
          <el-table-column prop="username" label="用户名" width="180" />
          <el-table-column prop="nickname" label="用户昵称" />
          <el-table-column prop="mobile" label="手机号" width="130" />
          <el-table-column prop="email" label="邮箱" width="200" />
          <el-table-column prop="avatar" label="头像" width="180">
            <template #default="scope">
              <el-avatar
                shape="square"
                size="large"
                :src="scope.row.avatar"
                @error="errorHandler"
              >
                <img
                  src="https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png"
                />
              </el-avatar>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" />
          <el-table-column prop="roleName" label="角色" />
          <el-table-column
            prop="createTime"
            label="创建时间"
            width="180"
            value-format="YYYY-MM-DD"
          />
          <el-table-column label="操作" width="180" fixed="right">
            <template #default="scope">
              <el-button link type="primary" icon="Edit" @click="EditSumbit(scope.row)"
                >修改</el-button
              >
              <el-button link type="primary" @click="Empowering(scope.row)"
                >赋能</el-button
              >
              <el-popconfirm title="确定要删除吗？" @confirm="handleDelete(scope.row)">
                <template #reference>
                  <el-button link type="primary" icon="Delete">删除</el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </el-main>
      <el-footer class="common-footer">
        <el-affix position="bottom" :offset="40">
          <el-pagination
            style="display: flex; justify-content: center; margin-top: 20px"
            v-model:current-page="queryParams.pageNum"
            v-model:page-size="queryParams.pageSize"
            :page-sizes="[5, 10, 15, 25]"
            size="default"
            :background="true"
            layout="sizes, prev, pager, next,jumper,total"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        /></el-affix>
      </el-footer>
    </el-container>
  </div>

  <!-- 修改用户信息 -->
  <el-dialog
    v-model="dialogVisible"
    title="修改用户信息"
    @close="resetForm(formRef)"
    style="min-width: 600px"
  >
    <el-form
      :model="form"
      ref="formRef"
      :rules="rules"
      label-width="auto"
      style="max-width: 600px"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item prop="username" label="用户名">
            <el-input v-model="form.username" disabled></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item prop="password" label="密码">
            <el-input v-model.trim="form.password" :disabled="userDisabled"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="nickname" label="用户昵称">
            <el-input v-model.trim="form.nickname" :disabled="userDisabled"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="mobile" label="手机号">
            <el-input v-model.trim="form.mobile" :disabled="userDisabled"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="email" label="邮箱">
            <el-input v-model.trim="form.email" :disabled="userDisabled"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="状态">
            <el-radio-group v-model="form.status" :disabled="userDisabled">
              <el-radio :value="0">禁用</el-radio>
              <el-radio :value="1">启用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item prop="avatar" label="头像">
            <el-upload
              class="avatar-uploader"
              action="/upload"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              :disabled="userDisabled"
            >
              <img
                v-if="form.avatar && userDisabled"
                :src="form.avatar"
                class="avatar"
                style="opacity: 0.5"
              />
              <img v-else-if="form.avatar" :src="form.avatar" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>
        </el-col>

        <el-divider />
        <el-col :span="12">
          <el-form-item prop="roleId" label="角色">
            <el-select
              v-model="form.roleId"
              placeholder="选择角色"
              size="large"
              style="width: 240px"
              :disabled="roleDisabled"
            >
              <el-option
                v-for="item in roleList"
                :key="item.value"
                :label="item.roleName"
                :value="item.roleId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-button type="primary" @click="submitForm(formRef)"> 确定 </el-button>
          <el-button @click="dialogVisible = false">取消</el-button>
        </el-col>
      </el-row>
    </el-form>
  </el-dialog>
</template>
<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
